# 多阶段构建
# 第一阶段：构建应用
FROM golang:1.20-alpine AS builder

# 设置工作目录
WORKDIR /app

# 安装构建依赖
RUN apk add --no-cache git ca-certificates tzdata

# 复制go mod文件
COPY go.mod go.sum ./

# 下载依赖
RUN go mod download

# 复制源代码
COPY . .

# 构建应用
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo \
    -ldflags="-w -s -X main.version=$(git describe --tags --always --dirty 2>/dev/null || echo 'dev') \
    -X main.buildTime=$(date -u '+%Y-%m-%d_%H:%M:%S') \
    -X main.gitCommit=$(git rev-parse --short HEAD 2>/dev/null || echo 'unknown')" \
    -o pi-mapper ./cmd/server

# 第二阶段：运行时镜像
FROM alpine:latest

# 安装运行时依赖
RUN apk --no-cache add ca-certificates tzdata

# 创建非root用户
RUN addgroup -g 1000 appgroup && \
    adduser -D -s /bin/sh -u 1000 -G appgroup appuser

# 设置工作目录
WORKDIR /app

# 创建必要的目录
RUN mkdir -p /app/logs /app/configs /app/videos

# 复制二进制文件
COPY --from=builder /app/pi-mapper /app/pi-mapper

# 复制配置文件
COPY --from=builder /app/configs/config.yml /app/configs/config.yml

# 设置权限
RUN chown -R appuser:appgroup /app

# 切换到非root用户
USER appuser

# 暴露端口
EXPOSE 8080

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD wget --quiet --tries=1 --spider http://localhost:8080/health || exit 1

# 设置环境变量
ENV TZ=Asia/Shanghai
ENV CONFIG_FILE=/app/configs/config.yml

# 启动应用
CMD ["./pi-mapper", "-config", "/app/configs/config.yml"]